package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/17 14:10
 */
public class DWMUserJumpDetailApp extends BaseApp {
    public static void main(String[] args) {
        new DWMUserJumpDetailApp().init(20002, 2, "DWMUserJumpDetailApp", "DWMUserJumpDetailApp", "dwd_page_log");
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    DataStreamSource<String> sourceStream) {
        /*sourceStream = sourceStream =
            env.fromElements(
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000}",
                *//*"{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"home\"},\"ts\":20000} ",*//*
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"detail\"},\"ts\":50000} "
            );
    
    */
        final KeyedStream<JSONObject, String> jsonObjKS = sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((ele, recordTimestamp) -> ele.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"));
        
        // 1. 创建模式
        //  首页->其他页面
        final Pattern<JSONObject, JSONObject> pattern = Pattern
            .<JSONObject>begin("start")
            .where(new SimpleCondition<JSONObject>() {
                @Override
                public boolean filter(JSONObject value) throws Exception {  // 找到首页
                    final String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return lastPageId == null || lastPageId.isEmpty();
                }
            })
            .next("next")
            .where(new SimpleCondition<JSONObject>() {
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    final String pageId = value.getJSONObject("page").getString("page_id");
                    return pageId != null && !pageId.isEmpty();
                }
            })
            .within(Time.seconds(10));
        
        //  把模式运用在流上, 返回一个模式流
        final PatternStream<JSONObject> ps = CEP.pattern(jsonObjKS, pattern);
        // 3. 从模式流中选出想要的数据
        ps
            .select(
                new OutputTag<JSONObject>("timeout") {},
                new PatternTimeoutFunction<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject timeout(Map<String, List<JSONObject>> pattern,
                                              long timeoutTimestamp) throws Exception {
                        final List<JSONObject> starts = pattern.get("start");
                        return starts.get(0);
                    }
                },
                new PatternSelectFunction<JSONObject, Object>() {
                    @Override
                    public Object select(Map<String, List<JSONObject>> pattern) throws Exception {
                        // 无需实现, 数据不需要
                        return null;
                    }
                }
            )
            .getSideOutput(new OutputTag<JSONObject>("timeout") {})
            .map(obj -> JSON.toJSONString(obj))
            .addSink(MyKafkaUtil.getFlinkKafkaSink("dwm_user_jump_detail"));
        
    }
}
/*
ps
            .flatSelect(
                new OutputTag<JSONObject>("timeout") {},
                new PatternFlatTimeoutFunction<JSONObject, JSONObject>() {
                    @Override
                    public void timeout(Map<String, List<JSONObject>> pattern,
                                        long timeoutTimestamp,
                                        Collector<JSONObject> out) throws Exception {
                        
                    }
                },
                new PatternFlatSelectFunction<JSONObject, Object>() {
                    @Override
                    public void flatSelect(Map<String, List<JSONObject>> pattern,
                                           Collector<Object> out) throws Exception {
                        
                    }
                }
            );
 */